<?php

class Login extends Controller {
	
	function index()
	{
		$data['main_content'] = 'login_form';
		$this->load->view('includes/template', $data);		
	}
	
	////////////////////////////////////////////////////////////////////////////
	
function validate_credentials()
	{		
		$this->load->model('membership_model');
		$query = $this->membership_model->validate();
		
		if($query) // if the user's credentials validated...
		{
			$data = array(
				'login' => $this->input->post('login'),
				'is_logged_in' => true,
				'user_id' => $this->user_id('login')
			);
			$this->session->set_userdata($data);
			redirect('site/members_area');
		}
		else // incorrect username or password
		{
			$this->index();
		}
		//redirect('site/members_area');
	}	
	
	//////////////////////////////////////////////////////////////////////////////
	
	function signup()
	{
		$data['main_content'] = 'signup_form';
		$this->load->view('includes/template', $data);
	}
	
	///////////////////////////////////////////////////////////////////////////////
	
	function create_member()
	{
		$this->load->library('form_validation');
		
		// field name, error message, validation rules
		$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('email', 'Email Adress', 'trim|required|valid_email|xss_clean');
		$this->form_validation->set_rules('login', 'Username', 'trim|required|min_length[4]|strtolower|callback_username_not_exists|xss_clean');
		$this->form_validation->set_rules('pwd', 'Password', 'trim|required|min_length[4]|max_length[32]|xss_clean');
		$this->form_validation->set_rules('pwd2', 'Password Confirmation', 'trim|required|matches[pwd]|xss_clean');
		
		
		if($this->form_validation->run() == FALSE)
		{
			$this->load->view('signup_form');
		}
		
		else
		{			
			$this->load->model('membership_model');
			
			if($query = $this->membership_model->create_member())
			{
				$data['main_content'] = 'signup_successful';
				$this->load->view('includes/template', $data);
			}
			else
			{
				$this->load->view('signup_form');			
			}
		}
		
	}
	
	function username_not_taken($login)
	{
		$this->form_validation->set_message('login', 'That %s already exists. Please chose a different username and try again.');

		if ($this->membership_model->taken_username($login))
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	function user_id($login)
	{
		return $this->membership_model->get_user_id($login);
	}
	
	//////////////////////////////////////////////////////////////////////////////
	
	function logout()
	{
		$this->session->sess_destroy();
		$this->index();
	}

	//////////////Test////////////////////////////////////////////////////////////
	function test()
	{
		$data['main_content'] = 'signup_successful';
		$this->load->view('includes/template', $data);
	}

}
